package org.springblade.modules.mes.base.utils;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.mes.base.entity.ProducePlan;
import org.springblade.modules.mes.base.service.IProducePlanService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class OverlapUtil {


	private static IProducePlanService service;

	private static IProducePlanService getService() {
		if (service == null) {
			service = SpringUtil.getBean(IProducePlanService.class);
		}
		return service;
	}

	/**
	 * 是否覆盖
	 *
	 * @param plan
	 * @return
	 */
	public static boolean overlap(ProducePlan plan) {
		Date begin = DateUtil.beginOfDay(plan.getProdTime());
		Date end = DateUtil.offsetDay(begin, 1);
		List<ProducePlan> dataList = getService().list(new QueryWrapper<ProducePlan>().lambda()
			.eq(ProducePlan::getProdCode, plan.getProdCode())
			.lt(ProducePlan::getProdTime, end)
			.ge(ProducePlan::getProdTime, begin));
		List<ProducePlan> actList = new ArrayList<>();
		for (ProducePlan data : dataList) {
			//同一个id的跳过
			if (data.getId().equals(plan.getId())) {
				continue;
			}
			if (data.getStatus() > 10) {
				continue;
			}
			actList.add(data);
		}
		List<Long> codeList = new ArrayList<>();
		Long b = 100000000L;
		for (ProducePlan data : actList) {
			long start1 = b + data.getBeginIdx();
			for (int i = 0; i < data.getCreateNumber(); i++) {
				codeList.add(start1 + i);
			}
		}
		long start2 = b + plan.getBeginIdx();
		for (int i = 0; i < plan.getCreateNumber(); i++) {
			if (codeList.contains(start2 + 1)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 需要生产订单数据
	 *
	 * @param plan
	 * @return
	 */
	public static boolean publish(ProducePlan plan) {
		Date begin = DateUtil.beginOfDay(plan.getProdTime());
		Date end = DateUtil.offsetDay(begin, 1);
		List<ProducePlan> dataList = getService().list(new QueryWrapper<ProducePlan>().lambda()
			.eq(ProducePlan::getProdCode, plan.getProdCode())
			.lt(ProducePlan::getProdTime, end)
			.ge(ProducePlan::getProdTime, begin));
		List<ProducePlan> actList = new ArrayList<>();
		for (ProducePlan data : dataList) {
			//同一个id的跳过
			if (data.getId().equals(plan.getId())) {
				continue;
			}
			if (data.getStatus() > 10) {
				continue;
			}
			actList.add(data);
		}
		List<Long> codeList = new ArrayList<>();
		Long b = 100000000L;
		for (ProducePlan data : actList) {
			long start1 = b + data.getBeginIdx();
			for (int i = 0; i < data.getCreateNumber(); i++) {
				codeList.add(start1 + i);
			}
		}
		long start2 = b + plan.getBeginIdx();
		for (int i = 0; i < plan.getCreateNumber(); i++) {
			if (codeList.contains(start2 + 1)) {
				return true;
			}
		}
		return false;
	}
}
